const { get: requestGet } = require('axios');
let YAML = require('yamljs')
let { resolve } = require('path')
let config = YAML.load(resolve(__dirname, '..', 'project.yaml'))
const { appID, appsecret } = config;
const url = `https://api.weixin.qq.com/cgi-bin/token`;
const cacheFile = resolve(__dirname, '..', '.project_cache')
const fs = require('fs');
const { get: memGet, set: memSet } = require('./mem');

const [accessCacheKey,ticketCacheKey] = ['accessToken','ticketToken'];
/**
 * 获取access_token
 */
async function origin() {
    return await requestGet(url, {
        params: {
            grant_type: 'client_credential'
            , appid: appID
            , secret: appsecret
        }
    });
}
/**
 * 从微信服务器获取ticket
 */
async function ticketOrigin(){
    const url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket';
    const access_token = await getAccessToken();
    return await requestGet(url,{
        params: {
            access_token,
            type: 'jsapi'
        }
    });
}
/**
 * { access_token:
   '32_qKRfwR_IRDjXZJ_VwoKMc8ZgtTgIRW3PVkqFYfoQSiJ2C89BSX4_aqzUFyX5ZOPIAy6u71tnUceXutyCBbHxnsVAog6rUWQMhn56RjHg5kiwM3OBbElgwZ3ce4UMQqoKh2ZvbcY82Nrgrw9CKPXhAAAFKS',
  expires_in: 1587742369017 }
 */
async function getAccessToken() {

    const token = await memGet(accessCacheKey);

    if (token) {
        console.log("get token from cache!");
        return token['value'];
    } else {
        const response = await origin();
        let { access_token, expires_in } = response.data;
        let r = await memSet(accessCacheKey, access_token, expires_in - 300);
        if (r) {
            console.log("get token from origin!");
            return access_token;
        }
    }
    throw "cannot get access_token";

}

async function getTicket(){
    const ticketCache = await memGet(ticketCacheKey);
    if(ticketCache){
        console.log("get ticket from cache!");
        return ticketCache['value'];
    }else{
        const response = await ticketOrigin();
        const {errmsg, ticket, expires_in}=response.data;
        if(errmsg!="ok"){
            throw "cannot get ticket from origin";
        }
        const r = memSet(ticketCacheKey, ticket, expires_in-300);
        if(r){
            console.log("get ticket from origin!");
            return ticket;
        }
    }
    throw "cannot get ticket";
}

(async ()=>{
    const token = await getAccessToken();
    console.log(token);
})()
module.exports = {
    getAccessToken, getTicket
}
    